<template>
  <div class="pdf-marking-box" @contextmenu.prevent>
    <div class="tool-box" :style="{height:toolboxHeight}">
      <div class="tool-box-item" @click="zoomin">放大</div>
      <div class="tool-box-item" @click="zoomout">缩小</div>
      <div class="tool-box-item" @click="skipPage(5)">跳到第6页</div>
      <div class="tool-box-item" :class="{active:isAddXc}" @click="isAddXc=!isAddXc">添加瑕疵</div>
    </div>
    <div class="container-box" ref="containerBox" @wheel="handleMouseWheel">
      <vue-resize-sensor initial @resize="handleContainerBoxResize"/>
      <!--<div class="eventMask"-->
      <!--     ref="eventMask"-->
      <!--     @wheel="handleMouseWheel"-->
      <!--     :style="{height:stageSize.height+'px',width:stageSize.width+'px'}"></div>-->
      <div class="page-list" ref="pageList" :style="{transform:`translate3d(0,-${scrollTop}px,0)`}">
        <div ref="pages" :style="{flexShrink:0,height:maxHeight*scale+'px',width:maxWidth*scale+'px'}"
             v-for="item in dataList"
             :key="item.pageIndex">
          <page-view v-if="item.pageIndex>=currPageIndex-pageCount/2&&item.pageIndex<=currPageIndex+pageCount/2"
                     :ref="'pageViews'+item.pageIndex" :data="item"/>
        </div>
      </div>
    </div>
    <div class="debug-info">
      <div class="debug-info__item">当前页：{{currPageIndex+1}}/{{dataList.length}}</div>
      <div class="debug-info__item">当前比例：{{scale}}</div>
      <div class="debug-info__item">当前滚动高度：{{scrollTop}}</div>
      <div class="debug-info__item">当前进度：{{(progress*100).toFixed(2)}}%</div>
    </div>
  </div>
</template>

<script>
  import vueResizeSensor from 'vue-resize-sensor'
  import PageView from "./PageView";
  import {v4 as uuid} from 'uuid'
  import {EventEmitter} from 'events'
  import {addEventListener, removeEventListener} from "@/util/eventManager";

  export const SCRAWLTYPE = {
    Line: 'Line',
    Rect: 'Rect',
    Arrow: 'Arrow',
    Ellipse: 'Ellipse',
    Eraser: 'Eraser'
  }
  export const POINTERTYPE = {
    hand: 'hand',
    text: 'text'
  }
  export const SCALETYPE = {
    'page-fit': 'page-fit', // 适合页面
    'pageFit': 'page-fit', // 适合页面
    'page-actual': 'page-actual',// 原始大小
    'pageActual': 'page-actual',// 原始大小
    'page-width': 'page-width', //适合页宽
    'pageWidth': 'page-width', //适合页宽
  }

  export default {
    components: {vueResizeSensor, PageView},
    data () {
      return {
        dataList: [],
        stageSize: {height: 0, width: 0},
        markList: [],
        markShow: true,
        maxWidth: 2479,
        maxHeight: 3508,
        eventBus: new EventEmitter(),
        privateData: {
          scaleType: 'page-fit',
          scrollTop: 0
        },
        pointerType: 'text',
        moveTask: '',
        oldMoveTask: '',
        hm: null,
        pageCount: 5,
        scrollHeight: 0,
        // progress: 0,
        isAddXc: false,
        autoScrollViewing: null,
      }
    },
    computed: {
      _minScale () {
        return this.minScale || Math.min(this.stageSize.width / this.maxWidth, this.stageSize.height / this.maxHeight)
      },
      scale () {
        if (!this.maxHeight) return 1
        let scaleType = this.scaleType
        if (scaleType === SCALETYPE.pageActual) return 1
        else if (scaleType === SCALETYPE.pageWidth) {
          return stageSize.width / this.maxWidth
        } else if (typeof scaleType === 'number') {
          return scaleType
        } else {
          return Math.min(this.stageSize.width / this.maxWidth, this.stageSize.height / this.maxHeight)
        }
      },
      scaleType: {
        get () {
          return this.privateData.scaleType
        },
        set (val) {
          if (typeof val === 'number') {
            if (val < this._minScale) val = this._minScale
            else if (val > this.maxScale) val = this.maxScale
          }
          this.privateData.scaleType = val
        }
      },
      scrollTop: {
        get () {
          return this.privateData.scrollTop
        },
        set (val) {
          this.$nextTick(() => {
            let pageList = this.$refs.pageList
            let max = pageList.scrollHeight - pageList.offsetHeight
            if (val < 0) val = 0
            else if (val > max) val = max
            this.privateData.scrollTop = val
            this.scrollHeight = max
          })
        }
      },
      progress () {
        return this.scrollTop / this.scrollHeight
      },
      currPageIndex () {
        if (!this.maxHeight) return 0
        let p = (this.scrollTop + this.stageSize.height / 2) / this.maxHeight / this.scale
        return Math.floor(p) || 0
      },
    },
    watch: {
      scale () {
        this.$nextTick(() => this.scrollTop = this.privateData.scrollTop)
      },
      currPageIndex () {
        this.sendEvent('page-change', this.currPageIndex)
      },
      progress () {
        this.sendEvent('progress-change', {
          scrollHeight: this.scrollHeight,
          pageIndex: this.currPageIndex,
          progress: this.progress
        })
      },
    },
    mounted () {
      // window.addEventListener("touchstart", this.preventDefault,
      //   {passive: false})
      // this.hm = new Hammer.Manager(this.$refs.eventMask)
      // this.hm = new Hammer.Manager(this.$refs.pageList)
      // this.hm.add(new Hammer.Pan())
      // this.hm.add(new Hammer.Tap())
      // this.hm.add(new Hammer.Press())
      // this.hm.on('tap', this.onTap)
      // this.hm.on('panstart', this.onPanstart)
      // this.hm.on('press', this.onPress)
      // this.addMark({start: '0-20', end: '0-30'})
      // this.eventBus.on('select-text-start', this.startSelectText)
    },
    methods: {
      getImgSrc (arg) {
        if (this.imageLoadFn && typeof this.imageLoadFn === 'function') {
          return this.imageLoadFn(arg)
        }
        return arg
      },
      async getText (pageIndex) {
        // console.log(pageIndex)
        if (this.textLoadFn && typeof this.textLoadFn === 'function') {
          let text = await this.textLoadFn(pageIndex)
          this.dataList[pageIndex].text = text
        }
        // return this.dataList[pageIndex].text
      },
      setScrawlData () {
      },
      preventDefault (e) {
        if (e.cancelable) e.preventDefault()
      },
      getAllHeight () {
        let pageList = this.$refs.pageList
        if (!pageList) return 0
        return pageList.scrollHeight
      },
      getScrollHeight () {
        let pageList = this.$refs.pageList
        if (!pageList) return 0
        return pageList.scrollHeight - pageList.offsetHeight
      },
      clearSelection () {
        let index = this.markList.findIndex(item => item.markid === 'selection-mark')
        if (index > -1) this.markList.splice(index, 1)
      },
      openMask (move = () => ({}), up = () => ({})) {
        let mask = document.createElement('div')
        mask.style.backgroundColor = 'rgba(0,0,0,0.1)'
        mask.style.position = 'absolute'
        mask.style.left = 0
        mask.style.top = 0
        mask.style.right = 0
        mask.style.bottom = 0
        this.$refs.containerBox.appendChild(mask)

        let $move = e => {
          move(e)
        }
        let $up = e => {
          removeEventListener('mouseup', $up)
          removeEventListener('mousemove', $move)
          mask.remove()
          up(e)
        }
        addEventListener('mousemove', $move)
        addEventListener('mouseup', $up)
      },
      // onTap () {
      // console.log(this.getPointerPositionOnImage())
      // this.clearSelection()
      // },
      // onPanstart (e) {
      //   // this.clearSelection()
      //
      //   if (e.pointerType === 'touch') {
      //     this.handleMoveImage()
      //     return
      //   }
      //   this.handleSelectText()
      // },
      handleStageMousedown (evt) {
        this.stopAutoScrollView()
        this.clearSelection()
        const isTouch = evt.type === 'touchstart'
        if (this.isAddXc) {
          this.handleAddXc()
          return
        }
        if (isTouch) {
          this.handleMoveImage()
          return
        }
        this.handleSelectText()
      },
      handleAddXc () {
        let startP = this.getPointerPositionOnStageView()
        let startX = startP.x
        let startY = startP.y

        let redMask = document.createElement('div')
        redMask.style.backgroundColor = 'rgba(255,0,0,0.3)'
        redMask.style.boxSizing = 'border-box'
        redMask.style.border = '1px solid red'
        redMask.style.position = 'absolute'
        redMask.style.left = `${startX}px`
        redMask.style.top = `${startY}px`

        this.$refs.containerBox.appendChild(redMask)


        let width = 0
        let height = 0

        let x = startX
        let y = startY

        let startPageIndex = this.getPageIndexByPointerPosition()
        let pageIndex = startPageIndex

        let move = e => {
          let p = this.getPointerPositionOnStageView()
          width = p.x - startP.x
          height = p.y - startP.y

          pageIndex = Math.min(startPageIndex, this.getPageIndexByPointerPosition())

          x = startX
          y = startY

          if (width < 0) {
            x = startX + width
            width *= -1
          }
          if (height < 0) {
            y = startY + height
            height *= -1
          }

          redMask.style.left = `${x}px`
          redMask.style.top = `${y}px`
          redMask.style.width = `${width}px`
          redMask.style.height = `${height}px`
        }
        let up = e => {
          redMask.remove()
          for (let i = pageIndex; i < pageIndex + this.pageCount; i++) {

            let leftTopPos = this.posOnStageToImageGroup(i, {x, y})
            let rightBottomPos = this.posOnStageToImageGroup(i, {x: x + width, y: y + height})

            // console.log(x, y, width, height)
            // console.log(i, leftTopPos, rightBottomPos)
            let rect = {
              x: leftTopPos.x,
              y: leftTopPos.y,
              width: rightBottomPos.x - leftTopPos.x,
              height: rightBottomPos.y - leftTopPos.y,
            }
            if (rect.width && rect.height) {
              // console.log(rect, i)
              this.addMark({
                start: i,
                end: JSON.stringify(rect)
              })
            }
          }
        }
        this.openMask(move, up)

      },
      posOnStageToImageGroup (pageIndex, stagePos) {
        let pagePos = this.posOnStageToPageGroup(pageIndex, stagePos)
        let imagePos = this.posOnPageGroupToImageGroup(pageIndex, pagePos)
        return imagePos
      },
      posOnStageToPageGroup (pageIndex, stagePos) {
        let y = this.scrollTop + stagePos.y - pageIndex * this.maxHeight * this.scale
        let x = stagePos.x - (this.stageSize.width - this.maxWidth * this.scale) / 2
        if (x < 0) x = 0
        else if (x > this.maxWidth * this.scale) x = this.maxWidth * this.scale
        if (y < 0) y = 0
        else if (y > this.maxHeight * this.scale) y = this.maxHeight * this.scale
        return {x, y}
      },
      posOnPageGroupToImageGroup (pageIndex, pagePos) {
        let pageViews = this.$refs[`pageViews${pageIndex}`]
        if (!pageViews) return {x: 0, y: 0}
        let pageView = pageViews[0]
        if (!pageView) return {x: 0, y: 0}
        let imgSize = pageView.imgSize
        let offsetWidth = imgSize.width
        let offsetHeight = imgSize.height
        let deltaX = (this.maxWidth / pageView.imgScale - offsetWidth) / 2
        let deltaY = (this.maxHeight / pageView.imgScale - offsetHeight) / 2

        let x = (pagePos.x / this.scale / pageView.imgScale - deltaX)
        let y = (pagePos.y / this.scale / pageView.imgScale - deltaY)
        if (x < 0) x = 0
        else if (x > offsetWidth) x = offsetWidth
        if (y < 0) y = 0
        else if (y > offsetHeight) y = offsetHeight
        return {x, y}
      },
      handleStageContextmenu () {
        console.log('handleStageContextmenu')
      },
      async getWordByIndexPos (pos) {
        if (/^(\d+)-(\d+)$/.test(pos)) {
          let pageIndex = Number(RegExp.$1)
          let index = Number(RegExp.$2)

          let words = this.getWords(pageIndex)
          if (!words) return
          let word = words[index]
          if (!word) return
          return {
            ...word,
            pageIndex,
            index
          }
        }
      },
      getSelection () {
        let selection = this.markList.find(item => item.markid === 'selection-mark')

        if (!selection) return null

        return {
          start: selection.start,
          end: selection.end,
          text: selection.text
        }
      },
      handleContainerBoxResize (size) {
        this.$nextTick(() => this.stageSize = size)
      },
      handleMouseWheel (e) {
        this.scrollTop += e.deltaY
      },
      getOffsetTop () {
        let offsetTop = 0
        let el = this.$refs.containerBox
        do offsetTop += el.offsetTop
        while ((el = el.parentElement))
        return offsetTop
      },
      getPointerPositionOnStageView (e) {
        let ev = e || event
        if (ev.changedTouches) {
          ev = ev.changedTouches[0]
        } else if (ev.changedPointers) {
          ev = ev.changedPointers[0]
        }
        return {
          x: ev.clientX || ev.pageX,
          y: (ev.clientY - this.getOffsetTop()) || ev.pageY
        }
      },
      getPointerPositionOnPageGroup (e) {
        let pointerPositionOnStage = this.getPointerPositionOnStageView(e)
        let pageIndex = this.getPageIndexByPointerPosition(e)
        return this.posOnStageToPageGroup(pageIndex, pointerPositionOnStage)
      },
      getPointerPositionOnImage (e) {
        let pointerPositionOnPageGroup = this.getPointerPositionOnPageGroup(e)
        let pageIndex = this.getPageIndexByPointerPosition(e)
        return this.posOnPageGroupToImageGroup(pageIndex, pointerPositionOnPageGroup)
      },
      getPageIndexByPointerPosition (e) {
        let pointerPositionOnStage = this.getPointerPositionOnStageView(e)
        let currPosition = pointerPositionOnStage.y + this.scrollTop
        return Math.floor(currPosition / this.maxHeight / this.scale)
      },
      scrollTo ({x, y}) {
        if (y !== undefined) this.scrollTop = y
      },
      scrollBy ({x, y}) {
        if (y !== undefined) this.scrollTop += y
      },

      handleMoveImage () {
        const scrollTop = this.scrollTop
        let evt = event.changedTouches[0]
        let startScreenY = evt.pageY

        let startTime = Date.now()
        let deltaY = 0

        const move = e => {
          deltaY = e.pageY - startScreenY
          this.scrollTo({y: scrollTop - deltaY})
        }
        const up = e => {
          let deltaTime = Date.now() - startTime
          this.stopAutoScrollView()
          if (deltaTime < 300) this.autoScrollView(deltaY / deltaTime)
        }
        this.openMask(move, up)
      },
      stopAutoScrollView () {
        if (this.autoScrollViewing) clearTimeout(this.autoScrollViewing)
      },
      autoScrollView (yv0 = 0, xv0 = 0) {
        if (this.autoScrollViewing) clearTimeout(this.autoScrollViewing)
        // this.log('yv0：', yv0, 'xv0：', xv0)
        let ya = 0.003 * (yv0 > 0 ? -1 : 1)
        let xa = 0.003 * (xv0 > 0 ? -1 : 1)
        let startTime = Date.now()
        const getPlusMinus = n => {
          if (Number(n) > 0) return 1
          else if (Number(n) < 0) return -1
          else if (Number(n) === 0) return 0
        }

        let scrollTop = this.scrollTop
        let scrollLeft = this.scrollLeft

        let ys = 0
        let xs = 0
        let oldYs = 0
        let oldXs = 0
        const fn = () => {
          this.autoScrollViewing = setTimeout(() => {
            let t = Date.now() - startTime
            let yv = yv0 + ya * t
            let xv = xv0 + xa * t
            if (getPlusMinus(yv) === getPlusMinus(yv0)) {
              oldYs = ys
              ys = yv0 * t + 0.5 * ya * t * t
            }
            if (getPlusMinus(xv) === getPlusMinus(xv0)) {
              oldXs = xs
              xs = xv0 * t + 0.5 * xa * t * t
            }

            // if ((oldXs === xs) && (oldYs === ys)) return

            if ((getPlusMinus(yv) !== getPlusMinus(yv0) && getPlusMinus(xv) !== getPlusMinus(xv0))) return
            //
            // let xs = xv0 * t + 0.5 * xa * t * t
            this.scrollTo({
              y: scrollTop - ys / this.scale,
              x: scrollLeft - xs / this.scale
            })
            // this.log('yv：', yv, 'ys：', ys, 'xs：', xs)
            fn()
          }, 17)
        }
        fn()
      },
      handleSelectText (e) {
        let A = this.getWordByPointerPosition(e)
        const move = async () => {
          // if (ev.type === 'touchmove') ev = ev.targetTouches[0]

          let pointerPositionOnStage = this.getPointerPositionOnStageView()
          let B = this.getWordByPointerPosition()
          if (!B) return
          if (!A) A = B

          let pos = this.getPos(A, B)
          if (!pos) return

          this.addMark({
            markid: 'selection-mark',
            start: pos.start,
            end: pos.end,
            config: {
              stroke: '',
              strokeWidth: 0,
              fill: this.selectionBgColor,
              name: 'selection'
            }
          })
          if (this.wholePage) return
          if (pointerPositionOnStage.y + 30 > this.stageSize.height) {
            this.scrollBy({y: 15 / this.scale})
          } else if (pointerPositionOnStage.y - 30 < 0) {
            this.scrollBy({y: -15 / this.scale})
          }
          if (pointerPositionOnStage.x + 50 > this.stageSize.width) {
            this.scrollBy({x: 15 / this.scale})
          } else if (pointerPositionOnStage.x - 50 < 0) {
            this.scrollBy({x: -15 / this.scale})
          }
        }
        const up = () => {
          // this.hm.off('panmove', move)
          // this.hm.off('panend', up)
          // removeEventListener('mousemove', move)
          // removeEventListener('mouseup', up)

          let selection = this.getSelection()
          if (selection) this.sendEvent('selection-change', selection)
        }

        this.openMask(move, up)
        // addEventListener('mousemove', move)
        // addEventListener('mouseup', up)
        // this.hm.on('panmove', move)
        // this.hm.on('panend', up)
      },
      sendEvent () {
        this.$emit(...arguments)
      },
      skipPage (pageIndex) {
        this.scrollTo({
          y: pageIndex * this.maxHeight * this.scale
        })
      },
      zoomin () {
        let scale = this.scale
        if (scale > 2.5) scale += 1
        else if (scale > 1.75) scale += 0.5
        else if (scale > 1.15) scale += 0.25
        else if (scale > 1) scale += 0.15
        else if (scale > 0.75) scale += 0.1
        else scale += 0.05
        this.scaleType = scale
      },
      zoomout () {
        let scale = this.scale
        if (scale > 3) scale -= 1
        else if (scale > 2) scale -= 0.5
        else if (scale > 1.25) scale -= 0.25
        else if (scale > 1.1) scale -= 0.15
        else if (scale > 0.8) scale -= 0.1
        else scale -= 0.05
        this.scaleType = scale
      },

      getWordByPointerPosition (e) {
        let pageIndex = this.getPageIndexByPointerPosition(e)
        let words = this.getWords(pageIndex)
        if (!words) return

        let pointerPositionOnImage = this.getPointerPositionOnImage(e)
        if (!pointerPositionOnImage) return

        for (let i = 0; i < words.length; i++) {
          let word = words[i]
          //字内
          if (pointerPositionOnImage.x >= word.x1 && pointerPositionOnImage.x <= word.x2 && pointerPositionOnImage.y >= word.y1 && pointerPositionOnImage.y <= word.y2) {
            return {
              position: pointerPositionOnImage.x > (word.x1 + word.x2) / 2 ? 'right' : 'left',
              ...word
            }
          }
        }
        let prevRowIndex = -1
        let minLineHeight = this.maxHeight * this.scale
        for (let i = 0; i < words.length; i++) {
          let word = words[i]
          // 行内
          if (pointerPositionOnImage.y >= word.y1 && pointerPositionOnImage.y <= word.y2) {
            prevRowIndex = word.rowIndex
            break
          } else {
            // 判断最小间隙
            if (prevRowIndex !== word.rowIndex) {
              // 换行了
              if (pointerPositionOnImage.y - word.y2 > 0) {
                // 鼠标上面
                if (pointerPositionOnImage.y - word.y2 < minLineHeight) {
                  minLineHeight = pointerPositionOnImage.y - word.y2
                  prevRowIndex = word.rowIndex
                }
              } else if (word.y1 - pointerPositionOnImage.y > 0) {
                // 鼠标下面
                if (word.y1 - pointerPositionOnImage.y < minLineHeight) {
                  minLineHeight = word.y1 - pointerPositionOnImage.y
                  prevRowIndex = word.rowIndex
                }
              }
            }
          }
        }
        // 文字行prevRowIndex
        let rowWords = words.filter(word => prevRowIndex === word.rowIndex)

        // let pageViews = this.$refs[`pageViews${pageIndex}`]
        // let pageView = pageViews[0]

        let prevWordIndex = -1
        let minLineWidth = this.maxWidth

        for (let i = 0; i < rowWords.length; i++) {
          // 字内 // 字的左右之间
          let word = rowWords[i]
          if (pointerPositionOnImage.x >= word.x1 && pointerPositionOnImage.x <= word.x2) {
            // this.log('字上面', word)
            return {
              position: pointerPositionOnImage.x > (word.x1 + word.x2) / 2 ? 'right' : 'left',
              ...word
            }
          } else {
            let leftSpace = Math.abs(pointerPositionOnImage.x - word.x1)
            let rightSpace = Math.abs(pointerPositionOnImage.x - word.x2)
            let min = Math.min(leftSpace, rightSpace)
            if (min < minLineWidth) {
              minLineWidth = min
              prevWordIndex = i
            }
          }
        }

        let resWord = rowWords[prevWordIndex]

        if (Math.abs(pointerPositionOnImage.x - resWord.x1) < Math.abs(pointerPositionOnImage.x - resWord.x2)) {
          return {
            position: 'left',
            ...resWord
          }
        } else {
          return {
            position: 'right',
            ...resWord
          }
        }
      },
      getWords (pageIndex) {
        let data = this.dataList[pageIndex]
        if (!data) return
        let text = data.text
        if (!text) return
        if (!text.words) return
        return text.words.map((item, index) => {
          let x1 = item.x1
          let x2 = item.x2
          let y1 = item.y1
          let y2 = item.y2
          return {
            ...item,
            x1: Math.min(x1, x2),
            x2: Math.max(x1, x2),
            y1: Math.min(y1, y2),
            y2: Math.max(y1, y2),
            index,
            pageIndex
          }
        })
      },
      getPos (A, B) {
        if (A.pageIndex > B.pageIndex) {
          [A, B] = [B, A]
        } else if (A.pageIndex === B.pageIndex) {
          if (A.index > B.index) {
            [A, B] = [B, A]
          } else if (A.index === B.index) {
            return null
          }
        }
        if (A.pageIndex === B.pageIndex && A.index === B.index - 1) {
          if (A.position === 'right' && B.position === 'left') {
            return
          }
        }
        let start = `${A.pageIndex}-${A.index}`
        let end = `${B.pageIndex}-${B.index}`
        if (A.position === 'right') {
          let words = this.getWords(A.pageIndex)
          if (!words) return null
          if (A.index === words.length - 1) {
            // 最后一个字右边
            return null
          }
          start = `${A.pageIndex}-${A.index + 1}`
        }
        if (B.position === 'left') {
          if (B.index === 0) {
            // 第一个字左边
            return null
          }
          end = `${B.pageIndex}-${B.index - 1}`
        }

        return {start, end}
      },
      open ({data}) {
        this.dataList = data.map((item, index) => {
          return {
            ...item,
            pageIndex: index
          }
        })
      },

      async getWrodsAToB (A, B) {
        if (!A || !B) return
        if (A.pageIndex > B.pageIndex) {
          [A, B] = [B, A]
        } else if (A.pageIndex === B.pageIndex) {
          if (A.index > B.index) {
            [A, B] = [B, A]
          }
        }
        let tRows = {}

        // AB之间的页
        for (let pageIndex = A.pageIndex; pageIndex <= B.pageIndex; pageIndex++) {
          let data = this.dataList[pageIndex]
          let text = await data.text
          let start = 0
          let end = text.words.length - 1
          if (pageIndex === A.pageIndex && pageIndex === B.pageIndex) {
            start = A.index
            end = B.index
          } else if (pageIndex === A.pageIndex) {
            start = A.index
          } else if (pageIndex === B.pageIndex) {
            end = B.index
          }
          for (let index = start; index <= end; index++) {
            let word = text.words[index]

            if (B.pageIndex === A.pageIndex && B.index === A.index) {
              if (A.position && B.position && A.position === B.position) break
            } else {
              if (pageIndex === A.pageIndex && index === A.index) {
                if (A.position === 'right') continue
              }
              if (pageIndex === B.pageIndex && index === B.index) {
                if (B.position === 'left') continue
              }
            }

            let name = `${pageIndex}_${word.rowIndex}`

            // console.log(word)
            if (!tRows[name]) {
              tRows[name] = {
                page: pageIndex,
                x: word.x1,
                y: word.y1,
                width: 0,
                height: 0,
                text: '',
                start: `${pageIndex}-${index}`,
                end: ''
              }
            }
            tRows[name].width = word.x2 - tRows[name].x
            tRows[name].height = word.y2 - tRows[name].y
            tRows[name].text += word.text
            tRows[name].end = `${pageIndex}-${index}`
          }
        }
        return tRows
      },
      setPointerType (pointerType) {

      },
      addMark (mark) {
        mark = JSON.parse(JSON.stringify(mark))
        if (!mark.markid) mark.markid = uuid()
        // if (!mark.markline) mark.markline = {}
        if (!mark.config) mark.config = {}
        let index = this.markList.findIndex(item => item.markid === mark.markid)
        if (index > -1) {
          this.markList.splice(index, 1, mark)
        } else {
          this.markList.push(mark)
        }
      }
    },
    props: {
      alwaysShowMarkTypes: {
        type: Array,
        default: () => ([])
      },
      maxScale: {
        type: Number,
        default: 4
      },
      minScale: {
        type: Number,
        default: 0
      },
      selectionBgColor: {
        type: String,
        default: 'rgba(0,180,255,0.5)'
      },
      imageLoadFn: Function,
      textLoadFn: Function,
      toolboxHeight: {
        type: String,
        defalue: '30px'
      }
    }
  }
</script>

<style scoped lang="scss">
  .pdf-marking-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;
    position: relative;

    .tool-box {
      background-color: red;
      /*height: 30px;*/
      display: flex;
      align-items: center;
      overflow-x: auto;

      .tool-box-item {
        color: white;
        font-size: 12px;
        padding: 3px 10px;
        border-radius: 5px;
        margin-left: 10px;

        &:hover, &.active {
          color: black;
          background-color: #f4f4f4;
        }
      }
    }

    .container-box {
      background-color: #f4f4f4;
      flex: 1;
      overflow: hidden;
      display: flex;
      touch-action: none;
      /*flex-direction: column;*/
      /*align-items: center;*/
      /*justify-items: center;*/

      .eventMask {
        position: absolute;
        left: 0;
        top: 0;
      }

      .page-list {
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-items: center;
        /*pointer-events: none;*/
        /*touch-action: none;*/
      }
    }

    .debug-info {
      position: absolute;
      top: 50px;
      pointer-events: none;

      &__item {

      }
    }
  }
</style>
